<!--
 * @LastEditors: yuSeen
 * @LastEditTime: 2021-12-26 11:25:55
-->
<template>
    <transition-group name="list" tag="ul">
        <li
            v-for="(item, index) in messageList"
            :key="item.id"
            class="messageItem"
            :style="[getStyle(item, index)]"
        >
            <SvgIcon :name="typeIcon[item.type]" />
            <span class="ml-2 message">{{ item.message }}</span>
        </li>
    </transition-group>
</template>

<script lang='ts' setup>
import { ref, watch } from 'vue';
import SvgIcon from '../svgIcon/svgIcon.vue';
import Color from "color";
import { typeColor, typeIcon, IMessageItem } from './types'
const props = defineProps<
    {
        messageItem: IMessageItem
    }>()

const messageList = ref<IMessageItem[]>([])

// 此处使用watchEffect会死循环，因为需要同时监听和修改messageList
watch(() => props.messageItem, newVal => {
    setTimeout(() => {
        messageList.value.push(newVal)
    }, 20);
    setTimeout(() => {
        messageList.value = filterList(newVal.id)
    }, newVal.duration);
}, {
    immediate: true
})

const filterList = (id: number) => messageList.value.filter(item => item.id !== id)

// 计算样式
const getStyle = (messageItem: IMessageItem, index: number) => {
    const color = typeColor[messageItem.type]
    return {
        color,
        top: 60 + index * 10 + 'px',
        backgroundColor: Color(color).lighten(0.38).toString()
    }
}

</script>

<style scoped lang='scss'>
.messageItem {
    @apply relative w-52 flex items-center px-3 h-8 rounded shadow whitespace-nowrap overflow-hidden;
    margin-left: calc(50% - 104px);
    z-index: 1000;
}
</style>